package com.godofgamblers.hotelmanagementsystem.handler;


import com.godofgamblers.hotelmanagementsystem.dto.CheckUser;
import com.godofgamblers.hotelmanagementsystem.pojo.Code;
import com.godofgamblers.hotelmanagementsystem.pojo.Comment;
import com.godofgamblers.hotelmanagementsystem.pojo.User;
import com.godofgamblers.hotelmanagementsystem.pojo.User_Level;
import com.godofgamblers.hotelmanagementsystem.service.CartService;
import com.godofgamblers.hotelmanagementsystem.service.Order_ItemService;
import com.godofgamblers.hotelmanagementsystem.service.UserService;
import com.godofgamblers.hotelmanagementsystem.util.RegexUtil;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Data
@Controller
public class UserHandler {

    @Autowired
    private UserService userService;
    @Resource
    private CartService cartService;
    @Autowired
    private Order_ItemService order_itemService;


    //跳转到登录页面
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    //登录
    @RequestMapping("/loginCheck")
    @ResponseBody
    public int login(User user, String rmb, HttpServletRequest request, HttpSession session1) {
        System.out.println(rmb+"rmb+++++++++++");
        int info=0;
        System.out.println("登录+++"+user);
        Session session = SecurityUtils.getSubject().getSession();
        String reg= RegexUtil.REGEX_MOBILE;
        //判断验证码
        Object obj=request.getSession().getAttribute("code");
        if(obj==null){
            return info;
        }
        String code= (String) obj;
        if(!code.equalsIgnoreCase(user.getCode())){
            info=1;//验证码错误
            return info;
        }

        //普通帐号登录
        //用户名登录
            if(user.getUser_account().matches(RegexUtil.REGEX_USERNAME)){
                System.out.println("判断普通帐号登录");
                session.setAttribute("loginWay",1);
                cryptoPwd(user);
                //手机作为帐号登录
            }else if(user.getUser_account().matches(reg)&&user.getUser_password()!=null){
                System.out.println("手机帐号登录");
                session.setAttribute("loginWay",2);
                user.setCode_phone(user.getUser_account());
              User  user1=userService.findUserByPhone(user.getCode_phone());
              if(user1==null){
                  info=4;
                  return info;
              }
              user.setUser_account(user1.getUser_account());
              cryptoPwd(user);
            }

            //手机号码发送动态验证码登录
            if(user.getUser_account().matches(reg)&&user.getUser_password()==null){
                //手机动态验证码作为密码
                System.out.println("手机动态码登录");
                //将登录方式存入session
                session.setAttribute("loginWay",3);
                //判断手机动态验证码
                Object codePhone= session1.getAttribute("codePhone");
                if(codePhone==null){
                    info=0;
                    return info;
                }
                String codePhone1= (String) codePhone;
                if(!codePhone1.equals(user.getCode_phone())){
                    info=2;
                    return info;
                }
                user.setCode_phone(user.getUser_account());
                user=userService.findUserByPhone(user.getCode_phone());
                if(user==null){
                    info=4;
                    return info;
                }
            }

        System.out.println("这里是登录认证++++++"+user);

        //使用shrio进行身份验证
        Subject currentUser = SecurityUtils.getSubject();	//获取"当前用户"
        //判断是否认证过
        if (!currentUser.isAuthenticated()) {
            //没有认证
            System.out.println("没有认证");
            UsernamePasswordToken token =
                    new UsernamePasswordToken(user.getUser_account(),user.getUser_password());
            if (rmb!=null && rmb.length()!=0) {
                System.out.println("记住我");
                token.setRememberMe(true);//设置记住我
            }
        try {
                //进行认证
                currentUser.login(token);
                //如果不包异常，说明认证成功
                System.out.println("认证成功");
            } catch (Exception e){
                if (e instanceof UnknownAccountException
                        || e instanceof IncorrectCredentialsException) {
                    info=2;//帐号或密码错误
                    System.out.println("帐号密码错误");
                    return info;
                }else {
                    //抛异常
                    info=0;
                    e.printStackTrace();//根据实际情况自己处理
                    return  info;
                }
            }
        }
        //认证成功，或已认证跳到首页

        info=3;
        Object object =session.getAttribute("user");
        System.out.println("认证成功或已认证");
        if(object==null){
            return info;
        }

        User user1= (User) object;
        session1.setAttribute("username",user1.getUser_account());
        session1.setAttribute("userimage",user1.getUser_image());

       return info;
    }

    //注册
    @RequestMapping("/registerCheck")
    @ResponseBody
    public int register(User user,HttpServletRequest request){

        System.out.println(user);
        int row=0;
        System.out.println("注册");
        if(user==null){
            return row;
        }
        String account=user.getUser_account();
        String phone=user.getUser_phone();

       //先查询是否帐号存在
        User findUser=userService.findUserByAccount(account);
        System.out.println("帐号"+findUser);
        if(findUser!=null){
            //帐号存在
            row=1;
            return row;
        }
        //通过手机号查询用户
        User findUser1=userService.findUserByPhone(phone);
        if(findUser1!=null){
            //存在
            row=4;
            return 4;
        }
        //获取验证码真实验证码code，验证码判断
        Object obj=request.getSession().getAttribute("code");
        if(obj==null){
            return row;
        }
        String code= (String) obj;
        if(!code.equalsIgnoreCase(user.getCode())){
            row=2;
            return row;
        }

        //判断手机验证码
        Object obj1=request.getSession().getAttribute("codePhone");
        if(obj1==null){
            return 0;
        }
        String code_phone= (String) obj;
        if(code_phone.equals(user.getCode_phone())){
            row=3;
            return row;
        }

        //加密
        cryptoPwd(user);
       int num=userService.register(user);
     if(num>0){
         User user1=userService.findUserByAccount(user.getUser_account());
         userService.addUid(user1);
         row=5;
         return row;
     }
        return row;
    }


    //MD5加密
    private void cryptoPwd(User user){
        if(user.getUser_password()!=null){
            user.setUser_password(new SimpleHash("MD5",user.getUser_password(),"1024").toString());
        }
    }



    //发送手机验证码
    @RequestMapping("/getCode_phone")
    @ResponseBody
    public int phone_login(Code codes, HttpServletRequest request){
        //获取真实验证码
        int info=0;
        Object obj=request.getSession().getAttribute("code");
        if(obj==null){
            return info;
        }
        String code= (String) obj;
        //如果验证码不相等,返回1
        String rCode=codes.getCode();

        if(rCode==""||rCode==null||!rCode.equalsIgnoreCase(code)){
            info=1;
           return info;
        }
        String user_phone=codes.getUser_phone();
//        user_phone.equals(reg)
        String reg= RegexUtil.REGEX_MOBILE;
        if(!user_phone.matches(reg)){
            info=2;
            return info;
        }

        System.out.println("发送手机验证码");
        //获取手机随机码并保存
        String codePhone=getCode_phone();
        System.out.println("手机验证码++"+codePhone);
        request.getSession().setAttribute("codePhone",codePhone);
        info=3;
        try {
            //成功发送返回1
            if(sendCode(user_phone,codePhone)){
                System.out.println("发送成功");
                info=3;
              return info;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("发送失败");
        return info;
    }

    //获取手机验证码
    public static boolean sendCode(String code_phone , String code )throws Exception{
        System.out.println("获取手机验证码");
        String code_Str = URLEncoder.encode("#code#="+code, "utf-8");
//        System.out.println(code_Str);
        //准备URL对象，将接口包装在此对象中
        URL url = new URL("http://v.juhe.cn/sms/send?mobile="+code_phone+
                "&tpl_id=191956&tpl_value="+code_Str+"&key=75b92e36b282e0a3d7b06a294ea3ade1");
        //打开对象
//        System.out.println("url+++++++++++"+url);
        URLConnection connection = url.openConnection();
        //向服务器发送连接请求
        connection.connect();
        //获得服务器响应的数据
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
        StringBuffer buffer = new StringBuffer();
        String lineData = null;
        while((lineData=bufferedReader.readLine())!=null) {
            buffer.append(lineData);
        }
        System.out.println(buffer);
        //关闭连接对象
        bufferedReader.close();
        System.out.println("这是什么"+buffer.toString().indexOf("\"erroe_code\":0"));
        if(buffer.toString().indexOf("\"erroe_code\":0")==-1) {
            System.out.println("成功+++++++++++++++++");
            return true;//当调用改方法时返回true短信就发送成功了
        }
        return false;
    }




    //获取随机验证码
    public static String getCode_phone(){
        //开始生成随机数字 -- 验证码
        StringBuffer buffer = new StringBuffer();
        Random random = new Random(); //随机数字
        for(int i =0;i<6 ;i++) {
            //生成一个6位数的随机数
            buffer.append(random.nextInt(10));//范围0到10，不包括10 ；0-9
        }
        return buffer.toString();
    }

    //获取验证码
    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        //创建验证码对象
        String code=drawImg(outputStream);
        //获取真实验证码值
        System.out.println("真实验证码++"+code);
        request.getSession().setAttribute("code", code);
        //code.createCode();

        try {
            ServletOutputStream out = response.getOutputStream();
            outputStream.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //画验证码
    private String drawImg(ByteArrayOutputStream outputStream){
        String code="";
        for (int i = 0; i <4 ; i++) {
            code += randomChar();
        }
        int width=70;
        int height=25;
        //创建一个bufferImage对象
        BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        Font font=new Font("Times New Roman",Font.PLAIN,20);
        Graphics2D g= bufferedImage.createGraphics();
        g.setFont(font);
        Color color=new Color(66,2,82);
        g.setColor(color);
        g.setBackground(new Color(226,226,240));
        g.clearRect(0,0,width,height);
        FontRenderContext context=g.getFontRenderContext();
        Rectangle2D bounds=font.getStringBounds(code,context);
        double x=(width-bounds.getWidth())/2;
        double y=(height -bounds.getHeight())/2;
        double ascent=bounds.getY();
        double baseY=y-ascent;
        g.drawString(code,(int)x,(int)baseY);
        g.dispose();
        try {
            ImageIO.write(bufferedImage,"jpg",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  code;

    }
    //随机类
    private char randomChar(){
        Random random=new Random();
        String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
        return s.charAt(random.nextInt(s.length()));
    }


    //获取到用户的级别和会员等级
    @RequestMapping("/findLogin")
    @ResponseBody
    public User_Level findUserLevel(){
        System.out.println("jingrulp*******************");
        System.out.println("进入userlevel");
       Object obj = SecurityUtils.getSubject().getSession().getAttribute("user");
       if(obj==null){
           return null;
       }
        //通过用户信息查到该用户的会员级别以及享有的折扣
        User user = (User)obj;
        User_Level userLevel = cartService.findUserLevel(user);
        return userLevel;
    }

    /**
     * 查询用户是否存在
     * @param account   账号
     * @return  ModelAndView 保存用户检查信息，是否存在，会员等级，折扣
     */
    @RequestMapping("/checkUserState")
    @ResponseBody
    public CheckUser checkUserState(String account){
        CheckUser checkUser = new CheckUser();
        String result="该账户不存在！";
        //检查用户
        Map<String,Object> checkResult = userService.checkUserState(account);
        Object object=checkResult.get("checkResult");
        if(object!=null){
            result = String.valueOf(checkResult.get("checkResult"));
            checkUser.setResult(result);
        }else {
            String User_id = String.valueOf(checkResult.get("User_id"));
            String level_name= String.valueOf(checkResult.get("level_name"));
            String level_discount= String.valueOf(checkResult.get("level_discount"));
            result = "该用户为"+level_name+"，享受"+new BigDecimal(level_discount).multiply(new BigDecimal(10))+"折优惠！";
            checkUser.setLevel_name(level_name);
            checkUser.setLevel_discount(level_discount);
            checkUser.setUser_id(User_id);
            checkUser.setResult(result);
        }
        return checkUser;
    }

    @RequestMapping("/upload_pic")
    @ResponseBody
    public String uploadPic(@RequestParam("pic_img") MultipartFile picture, HttpServletRequest request) {
        System.out.println(picture);
        //储存图片
        String path = request.getServletContext().getRealPath("/");
        System.out.println("这是path"+path);
        System.out.println(path);
        File imageFile = new File(path + "images/user_images/");
        System.out.println("这是imageFile路径"+imageFile.toString());
        String picture_name = picture.getOriginalFilename();

        if (!imageFile.exists()) {
            imageFile.mkdirs();
        }

        //随机生成文件名
        String fileName = UUID.randomUUID().toString();
        fileName += picture_name.substring(picture_name.indexOf("."));

        //确定该文件的路径
        File upFile = new File(imageFile, fileName);
        System.out.println("这是文件的路径"+upFile.toString());
        //存放
        try {
            picture.transferTo(upFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Session session = SecurityUtils.getSubject().getSession();
        Object obj = session.getAttribute("user");
        User user = null;
        if (obj != null) {
            user = (User) obj;
        }
        user.setUser_image(fileName);

        userService.setHeadPicture(user);

        return "修改成功";
    }

    //用户在个人中心里面评论
    @RequestMapping("/usercommon")
    @ResponseBody
    public String addCommon(Integer order_item_id,String common,Integer room_type_id){
        System.out.println(order_item_id+common);
        order_itemService.updateOrderCommonState(order_item_id);//订单项改为已评论

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(date);

        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");

        //插入评论表
        Comment comment = new Comment();
        comment.setComment_context(common);
        comment.setRoom_type_id(room_type_id);
        comment.setUser_id(user.getUser_id());
        comment.setComment_time(time);
        order_itemService.insertCommon(comment);
        return "成功";
    }


    @RequestMapping("/user_image")
    @ResponseBody
    public String UserImage(){
        String image = "default.png";
        Session session = SecurityUtils.getSubject().getSession();
        Object obj = session.getAttribute("user");
        User user = null;
        if (obj != null) {
            user = (User) obj;
            image = userService.getUserImage(user.getUser_id());
        }

        return image;
    }
}
